package com.carlife.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.util.Log;

public class DateUtil {
	
	public static final String DF_ALL = "yyyy-MM-dd HH:mm:ss E";
	public static final SimpleDateFormat DEFATULT_FORMAT = new SimpleDateFormat(DF_ALL);
	public static final String DF_SHOW = "yyyy-MM-dd E";
	
	public static Date createDate(String dataStr, String formate) {
		try {
			SimpleDateFormat newFormate = new SimpleDateFormat(formate);
			return newFormate.parse(dataStr);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String currentTimeFormatted() {
		Date crnt = new Date();
		return DEFATULT_FORMAT.format(crnt);
	}
	
	public static String parseToFormat(String original, String newFormatStr) {
		try {
			SimpleDateFormat newFormate = new SimpleDateFormat(newFormatStr);
			return newFormate.format(DEFATULT_FORMAT.parse(original));
		} catch (ParseException e) {
			return original;
		}
	}
	
	public static String parseToFormat(String original, String oldFormatStr, String newFormatStr) {
		try {
			SimpleDateFormat oldFormat = new SimpleDateFormat(oldFormatStr);
			SimpleDateFormat newFormate = new SimpleDateFormat(newFormatStr);
			return newFormate.format(oldFormat.parse(original));
		} catch (ParseException e) {
			return original;
		}
	}
	
	
	public static double getIncreament(String start, String end) {
		try {
			Date startDate = DEFATULT_FORMAT.parse(start);
			Date endDate = DEFATULT_FORMAT.parse(end);
			Calendar d1 = Calendar.getInstance();
			d1.setTime(startDate);
			Calendar d2 = Calendar.getInstance();
			d2.setTime(endDate);
			
			boolean negative = false;

			if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
				java.util.Calendar swap = d1;
				d1 = d2;
				d2 = swap;
				negative = true;
			}
			
			int days = d2.get(java.util.Calendar.DAY_OF_YEAR)
					- d1.get(java.util.Calendar.DAY_OF_YEAR);
			int y2 = d2.get(java.util.Calendar.YEAR);
			if (d1.get(java.util.Calendar.YEAR) != y2) {
				d1 = (java.util.Calendar) d1.clone();
				do {
					days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
					d1.add(java.util.Calendar.YEAR, 1);
				} while (d1.get(java.util.Calendar.YEAR) != y2);
			}
			if (negative) {
				return 0-days;
			} else {
				return days;
			}
		} catch (ParseException e) {
			Log.e(Constants.LOG_TAG, e.getMessage(), e);
			return 0;
		}
	}

}
